package com.weimob.mcloud.wechatwork.customer.job;

import com.weimob.dq.client.api.DqFramework;
import com.weimob.elasticjob.annotation.ElasticJob;
import com.weimob.mcloud.wechatwork.common.utils.JsonUtil;
import com.weimob.mcloud.wechatwork.core.base.SingleRequest;
import com.weimob.mcloud.wechatwork.core.entity.config.clue.ClueCfg;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.CustomerProcess;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.CustomerStage;
import com.weimob.mcloud.wechatwork.core.enums.clue.PotentialSettingEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.ProcessStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerProcessService;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerStageRelationService;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerStageRemindRecordService;
import com.weimob.mcloud.wechatwork.core.service.customer.request.QueryCustomerProcessRequest;
import com.weimob.mcloud.wechatwork.core.service.customer.response.QueryCustomerProcessResponse;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.convertor.customer.CustomerProcessRequestBuilder;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户流程定时任务
 *
 * @author jiawei.you01
 * @date 2022/9/21 16:46
 * @since 1.0
 */
@Slf4j
@Component
public class CustomerProcessJob {


    @Resource
    PrivateSphereService privateSphereService;

    @Resource
    CustomerProcessService customerProcessService;

    @Resource
    CustomerStageRelationService customerStageRelationService;

    @Resource
    CustomerProcessRequestBuilder requestBuilder;

    @Resource
    CustomerStageRemindRecordService remindRecordService;

    @Resource
    private DqFramework dqClient;

    @Autowired
    @Qualifier("customerProcessThreadPool")
    private ThreadPoolTaskExecutor customerProcessThreadPool;

    @Value("${customer.stage.remind.openDelay:false}")
    private Boolean openDelay;


    /**
     * 提醒员工跟进客户流程定时任务
     * 每天晚上2点定时扫表，扫出如果符合当天需要发送消息的数据，则送入延时队列，到点发送
     */
    @ElasticJob(name = "remindEmployeeFollowUp", cron = "0 0 2 * * ?")
    public void remindEmployeeFollowUp() {
        //查询所有私域
        PrivateSphere queryRequest = new PrivateSphere();
        //只查有效的私域信息
        queryRequest.setStatus(1);
        SoaResponse<List<PrivateSphere>, Void> searchResponse = privateSphereService.simpleSearch(queryRequest);
        List<PrivateSphere> allPrivateSphere = SoaUtil.unpack(searchResponse);

        for (PrivateSphere privateSphere : allPrivateSphere) {
            SingleRequest<QueryCustomerProcessRequest> request = requestBuilder.buildQueryList(privateSphere);
            SoaResponse<QueryCustomerProcessResponse, Void> processListResponse = customerProcessService.queryAll(request);
            QueryCustomerProcessResponse response = SoaUtil.unpack(processListResponse);
            List<CustomerProcess> processList = response.getProcessList();
            if(CollectionUtils.isEmpty(processList)){
                continue;
            }
            for (CustomerProcess customerProcess : processList) {

                if(ProcessStatusEnum.VALID.equals(customerProcess.getStatusEnum())){
                    log.info("流程已关闭,processName:{},processId:{}",customerProcess.getProcessName(),customerProcess.getProcessId());
                    continue;
                }

                Map<String, List<ClueCfg>> stageClueCfgMap = customerProcess
                        .getCustomerStages()
                        .stream()
                        .collect(Collectors
                                .toMap(CustomerStage::getStageId, CustomerStage::getCfgList, (t1, t2) -> t1));

                for (String stageId : stageClueCfgMap.keySet()) {

                    ClueCfg followClueCfg = stageClueCfgMap.get(stageId).stream().filter(i ->
                            PotentialSettingEnum.CUSTOMER_PROCESS_FOLLOW.equals(i.getPotentialSettingEnum())).findAny().orElse(null);
                    if (followClueCfg == null || !followClueCfg.getRuleOpenFlag()) {
                        //如果客户没有打开跟进提醒，则直接返回
                        log.info("当前客户阶段跟进提醒没有打开,stageId:{},followClueCfg:{}", stageId, JsonUtil.obj2Str(followClueCfg));
                        continue;
                    }
                    /**
                     * 每一个的stage都的任务都交给线程池执行
                     */
                    customerProcessThreadPool
                            .execute(new RemindEmployeeFollowUpThread(privateSphere
                                    , customerStageRelationService
                                    , stageId
                                    , stageClueCfgMap.get(stageId)
                                    , remindRecordService
                                    , dqClient,openDelay));
                }
            }
        }


    }

}
